﻿using JsonConversion;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;
using RTracker.Models.Common;
using RTracker.Models.ErrorLog;
using System.Web.Security;
using RTracker.Models.Login;
using System.Threading;

namespace RTracker.Models.User
{
    public class MUser
    {
        /// static variable RowSize from config settings to get list of this row size.
        public static int nRowSize = Convert.ToInt32(ConfigurationManager.AppSettings["TotalRecordsInListUser"]);

        /// <summary>
        /// This method is used to create a user in the database.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCUser">This object contains details of the user.</param>
        /// <returns>CStatus which is an object that contain transaction details</returns>
        public CStatus CreateUser(CAuthenticationContext objCAuthenticationContext, ref CUser objCUser)
        {
            CStatus oCStatus = new CStatus();
            objCUser.LogonPassword = Membership.GeneratePassword(6, 2);

            // store password here in order to email it to user after successful account creation
            string strEmail = objCUser.EmailAddress;
            string strPassword = objCUser.LogonPassword;

            // objCUser contains encrypted password
            // objCUser.LogonPassword = MLogin.ComputePasswordHash(objCUser);   // working, tested
            
            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_create_user_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@organization_id", SqlDbType.Int).Value = objCUser.OrganizationId;
                    cmd.Parameters.Add("@first_name", SqlDbType.NVarChar).Value = objCUser.FirstName;
                    cmd.Parameters.Add("@last_name", SqlDbType.NVarChar).Value = objCUser.LastName;
                    cmd.Parameters.Add("@dob", SqlDbType.Date).Value = Convert.ToDateTime(objCUser.DOB);
                    cmd.Parameters.Add("@gender", SqlDbType.NVarChar).Value = objCUser.Gender;
                    cmd.Parameters.Add("@title", SqlDbType.NVarChar).Value = objCUser.Title;
                    cmd.Parameters.Add("@activation_date", SqlDbType.DateTime).Value = Convert.ToDateTime(objCUser.ActivationDate);
                    cmd.Parameters.Add("@expiration_date", SqlDbType.DateTime).Value = Convert.ToDateTime(objCUser.ExpirationDate);
                    cmd.Parameters.Add("@logon_name", SqlDbType.NVarChar).Value = objCUser.LogonName;
                    cmd.Parameters.Add("@logon_password", SqlDbType.NVarChar).Value = objCUser.LogonPassword;
                    cmd.Parameters.Add("@email_address", SqlDbType.NVarChar).Value = objCUser.EmailAddress;
                    cmd.Parameters.Add("@logon_status", SqlDbType.Int).Value = objCUser.LogonStatus;
                    //cmd.Parameters.Add("@password_change_timestamp", SqlDbType.DateTime).Value = objCUser.PasswordChangeTimestamp;
                    cmd.Parameters.Add("@user_account_status", SqlDbType.Int).Value = objCUser.UserAccountStatus;
                    cmd.Parameters.Add("@logon_locked", SqlDbType.Int).Value = objCUser.LogonLocked;
                    //cmd.Parameters.Add("@logon_locked_timestamp", SqlDbType.DateTime).Value = objCUser.LogonLockedTimestamp;
                    cmd.Parameters.Add("@change_password_next_logon", SqlDbType.Bit).Value = objCUser.ChangePasswordNextLogon;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;

                        // if user created, email password to user in background process
                        MEmail oMEmail = new MEmail();
                        Thread email = new Thread(delegate() 
                           {
                               oMEmail.SendConfirmationEmail(strEmail, strPassword);
                           });
                        email.IsBackground = true;
                        email.Start();
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                        //oCStatus.StatusDetails = CAppErrorsConstants.SomethingWentWrong;
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }


            return oCStatus;
        }

        /// <summary>
        /// This method is used to delete a user in the database.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCUser">This object contains details of the user.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus DeleteUser(CAuthenticationContext objCAuthenticationContext, ref CUser objCUser)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_delete_user_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCUser.CreatedBy;
                    cmd.Parameters.Add("@user_ids", SqlDbType.NVarChar).Value = objCUser.UserIds;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                        //oCStatus.StatusDetails = CAppErrorsConstants.SomethingWentWrong;
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }


            return oCStatus;
        }

        /// <summary>
        /// This method is used to update the user's detail in the database.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCUser">This object contains details of the user.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus UpdateUser(CAuthenticationContext objCAuthenticationContext, ref CUser objCUser)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_update_user_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.Add("@user_id", SqlDbType.Int).Value = objCUser.UserId;
                    cmd.Parameters.Add("@organization_id", SqlDbType.Int).Value = objCUser.OrganizationId;
                    cmd.Parameters.Add("@first_name", SqlDbType.NVarChar).Value = objCUser.FirstName;
                    cmd.Parameters.Add("@last_name", SqlDbType.NVarChar).Value = objCUser.LastName;
                    cmd.Parameters.Add("@dob", SqlDbType.Date).Value = DateTime.Parse(objCUser.DOB.Value.Date.ToString());
                    cmd.Parameters.Add("@gender", SqlDbType.NVarChar).Value = objCUser.Gender;
                    cmd.Parameters.Add("@title", SqlDbType.NVarChar).Value = objCUser.Title;
                    cmd.Parameters.Add("@activation_date", SqlDbType.DateTime).Value = DateTime.Parse(objCUser.ActivationDate.Value.ToString());
                    cmd.Parameters.Add("@expiration_date", SqlDbType.DateTime).Value = DateTime.Parse(objCUser.ExpirationDate.Value.ToString());
                    cmd.Parameters.Add("@logon_name", SqlDbType.NVarChar).Value = objCUser.LogonName;
                    //cmd.Parameters.Add("@logon_password", SqlDbType.NVarChar).Value = objCUser.LogonPassword;
                    cmd.Parameters.Add("@email_address", SqlDbType.NVarChar).Value = objCUser.EmailAddress;
                    cmd.Parameters.Add("@logon_status", SqlDbType.Int).Value = objCUser.LogonStatus;
                    //cmd.Parameters.Add("@password_change_timestamp", SqlDbType.DateTime).Value = objCUser.PasswordChangeTimestamp;
                    cmd.Parameters.Add("@user_account_status", SqlDbType.Int).Value = objCUser.UserAccountStatus;
                    cmd.Parameters.Add("@logon_locked", SqlDbType.Int).Value = objCUser.LogonLocked;
                    cmd.Parameters.Add("@logon_locked_timestamp", SqlDbType.DateTime).Value = objCUser.LogonLockedTimestamp;
                    cmd.Parameters.Add("@change_password_next_logon", SqlDbType.Bit).Value = objCUser.ChangePasswordNextLogon;
                    //cmd.Parameters.Add("@last_successful_logon_timestamp", SqlDbType.DateTime).Value = objCUser.LastSuccessfulLogonTimestamp;
                    //cmd.Parameters.Add("@last_successful_logout_timestamp", SqlDbType.DateTime).Value = objCUser.LastSuccessfulLogoutTimestamp;
                    //cmd.Parameters.Add("@logon_failure_count", SqlDbType.Int).Value = objCUser.LogonFailureCount;
                    //cmd.Parameters.Add("@is_system_generated", SqlDbType.Bit).Value = objCUser.IsSystemGenerated;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                        //oCStatus.StatusDetails = CAppErrorsConstants.SomethingWentWrong;
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }

            return oCStatus;
        }

        /// <summary>
        /// This method is used to get the user's detail in the database.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCUser">This object contains details of the user.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus GetUserDetail(CAuthenticationContext objCAuthenticationContext, ref CUser objCUser)
        {
            CStatus oCStatus = new CStatus();
            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand("r_get_user_detail_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.Add("@user_id", SqlDbType.Int).Value = objCUser.UserId;
                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;

                    SqlDataAdapter adp = new SqlDataAdapter(cmd);

                    DataTable dt = new DataTable();

                    int rowsAffected = adp.Fill(dt);

                    if (rowsAffected > 0)
                    {
                        objCUser = dt.ConvertToListFromDataTableUser()[0];
                    }

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.DetailSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// Sets the softlock on the record whose Id is passed.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCUser">This object contains details of the user.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus SetUserSoftLock(CAuthenticationContext objCAuthenticationContext, CUser objCUser)
        {
            CStatus oCStatus = new CStatus();
            
                using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
                {
                    try
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand("r_set_user_soft_lock_procedure", con);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@user_id", SqlDbType.NVarChar).Value = objCUser.UserId;
                        cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCUser.CreatedBy;

                        cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                        cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                        cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                        cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                        cmd.ExecuteNonQuery();

                        if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                        {
                            oCStatus.Success = true;
                            oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                        }
                        else
                        {
                            oCStatus.Success = false;
                            oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                            //oCStatus.StatusDetails = CAppErrorsConstants.SomethingWentWrong;
                        }
                    }
                    catch (Exception ex)
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = ex.Message;
                    }
                }
           

            return oCStatus;
        }

        /// <summary>
        /// Sets the hardlock on the record whose Id is passed.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCUser">This object contains details of the user.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus SetUserHardLock(CAuthenticationContext objCAuthenticationContext, CUser objCUser)
        {
            CStatus oCStatus = new CStatus();
           
                using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
                {
                    try
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand("r_set_user_hard_lock_procedure", con);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@user_id", SqlDbType.NVarChar).Value = objCUser.UserId;
                        cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCUser.CreatedBy;

                        cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                        cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                        cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                        cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                        cmd.ExecuteNonQuery();

                        if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                        {
                            oCStatus.Success = true;
                            oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                        }
                        else
                        {
                            oCStatus.Success = false;
                            oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                            //oCStatus.StatusDetails = CAppErrorsConstants.SomethingWentWrong;
                        }
                    }
                    catch (Exception ex)
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = ex.Message;
                    }
                }
            

            return oCStatus;
        }

        /// <summary>
        /// Releases the softlock on the record whose Id is passed.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCUser">This object contains details of the user.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus ReleaseUserSoftLock(CAuthenticationContext objCAuthenticationContext, CUser objCUser)
        {
            CStatus oCStatus = new CStatus();
            
                using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
                {
                    try
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand("r_release_user_soft_lock_procedure", con);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@user_id", SqlDbType.NVarChar).Value = objCUser.UserId;
                        cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCUser.CreatedBy;

                        cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                        cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                        cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                        cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                        cmd.ExecuteNonQuery();

                        if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                        {
                            oCStatus.Success = true;
                            oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                        }
                        else
                        {
                            oCStatus.Success = false;
                            oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                            //oCStatus.StatusDetails = CAppErrorsConstants.SomethingWentWrong;
                        }
                    }
                    catch (Exception ex)
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = ex.Message;
                    }
                }
            

            return oCStatus;
        }

        /// <summary>
        /// Releases the hardlock on the record whose Id is passed.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCUser">This object contains details of the user.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus ReleaseUserHardLock(CAuthenticationContext objCAuthenticationContext, CUser objCUser)
        {
            CStatus oCStatus = new CStatus();
            
                using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
                {
                    try
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand("r_release_user_hard_lock_procedure", con);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@user_id", SqlDbType.NVarChar).Value = objCUser.UserId;
                        cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCUser.CreatedBy;

                        cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                        cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                        cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                        cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                        cmd.ExecuteNonQuery();

                        if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                        {
                            oCStatus.Success = true;
                            oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                        }
                        else
                        {
                            oCStatus.Success = false;
                            oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                            //oCStatus.StatusDetails = CAppErrorsConstants.SomethingWentWrong;
                        }
                    }
                    catch (Exception ex)
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = ex.Message;
                    }
                }
            

            return oCStatus;
        }

        /// <summary>
        ///  This function is used to get complete User list
        /// </summary>
        /// <returns>List of type CUser</returns>
        public GUser GetUserGridList(CUser objCUser, CAuthenticationContext objCAuthenticationContext)
        {
            GUser objGUser = new GUser();
            int nTotalRecords = 0;
            int nCurrentRowSize = nRowSize;

            if (objCUser.RowSize != 0)
            {
                nCurrentRowSize = objCUser.RowSize;
            }
            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand("r_get_user_paging_list_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@user_id", SqlDbType.Int).Value = objCUser.UserId;
                    cmd.Parameters.Add("@organization_id", SqlDbType.Int).Value = objCUser.OrganizationId;
                    cmd.Parameters.Add("@page_number", SqlDbType.Int).Value = objCUser.PageNumber;
                    cmd.Parameters.Add("@row_size", SqlDbType.Int).Value = nCurrentRowSize;
                    cmd.Parameters.Add("@sort_on", SqlDbType.VarChar).Value = objCUser.SortOn;
                    cmd.Parameters.Add("@sort_type", SqlDbType.VarChar).Value = objCUser.SortType;
                    cmd.Parameters.Add("@search", SqlDbType.VarChar).Value = objCUser.Search;
                    cmd.Parameters.Add("@searchon", SqlDbType.VarChar).Value = objCUser.SearchOn;
                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;
                    SqlDataAdapter adp = new SqlDataAdapter(cmd);

                    DataTable dt = new DataTable();

                    int rowsAffected = adp.Fill(dt);

                    objGUser.Paging = new CPaging();
                    if (rowsAffected > 0)
                    {
                        objGUser.LstUser = dt.ConvertToListFromDataTableUser();
                        objGUser.LstUser[0].PageNumber = int.Parse(cmd.Parameters["@idOut"].Value.ToString());
                        objGUser.Paging.PageNumber = objGUser.LstUser[0].PageNumber;
                    }
                    else
                    {
                        objGUser.LstUser = null;
                    }

                    
                    nTotalRecords = int.Parse(cmd.Parameters["@error"].Value.ToString());

                    objGUser.Status = new CStatus();

                    if (nTotalRecords < 0)
                    {
                        objGUser.Status.Success = false;
                        objGUser.Status.StatusDetails = nTotalRecords.DbError();
                    }
                    else
                    {
                        objGUser.Paging.TotalRecordsCount = nTotalRecords;
                        objGUser.Paging.PageSize = nCurrentRowSize;

                        objGUser.Status.Success = true;
                        objGUser.Status.StatusDetails = "success";
                    }

                    

                }
                catch (Exception ex)
                {
                    objGUser.Status = new CStatus();
                    objGUser.Status.Success = false;
                    objGUser.Status.StatusDetails = ex.Message;
                }
            }
            return objGUser;
        }

        /// <summary>
        /// this function is used to create user session at login time
        /// in this we set parameters of session object through application variables.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCUser">This object contains details of the user.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus ChangePassword(CAuthenticationContext objCAuthenticationContext, CUser objCUser)
        {
            CStatus oCStatus = new CStatus();
            
                using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
                {
                    try
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand("r_change_user_password_procedure", con);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@user_id", SqlDbType.Int).Value = objCUser.UserId;
                        cmd.Parameters.Add("@logon_password", SqlDbType.NVarChar).Value = objCUser.LogonPassword;
                        cmd.Parameters.Add("@old_logon_password", SqlDbType.NVarChar).Value = objCUser.OldLogonPassword;
                        cmd.Parameters.Add("@password_change_purpose", SqlDbType.Int).Value = objCUser.PasswordChangePurpose;
                        cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCUser.CreatedBy;

                        cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                        cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                        cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                        cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                        cmd.ExecuteNonQuery();

                        if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                        {
                            oCStatus.Success = true;
                            oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                        }
                        else
                        {
                            oCStatus.Success = false;
                            oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                            //oCStatus.StatusDetails = CAppErrorsConstants.SomethingWentWrong;
                        }
                    }
                    catch (Exception ex)
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = ex.Message;
                    }
                }
            

            return oCStatus;
        }

        /// <summary>
        /// this function is used to logut user.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCUser">This object contains details of the user.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus UserLogout(CAuthenticationContext objCAuthenticationContext, CUser objCUser)
        {
            CStatus oCStatus = new CStatus();
            
                using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
                {
                    try
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand("r_user_logout_procedure", con);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@user_id", SqlDbType.Int).Value = objCUser.UserId;

                        cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                        cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                        cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                        cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                        cmd.ExecuteNonQuery();

                        if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                        {
                            oCStatus.Success = true;
                            oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                        }
                        else
                        {
                            oCStatus.Success = false;
                            oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                            //oCStatus.StatusDetails = CAppErrorsConstants.SomethingWentWrong;
                        }
                    }
                    catch (Exception ex)
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = ex.Message;
                    }
                }
           

            return oCStatus;
        }

        /// /// <summary>
        ///  This function is used to get complete User list working under a same organization.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCUser">This object contains details of the user.</param>
        /// <param name="lstCUser">"out" the list of users</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus GetUserList(CAuthenticationContext objCAuthenticationContext, CUser objCUser, out List<CUser> lstCUser)
        {
            CStatus oCStatus = new CStatus();
            lstCUser = new List<CUser>();
              using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
                {
                    try
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand("r_get_user_list_procedure", con);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@organization_id", SqlDbType.Int).Value = objCUser.OrganizationId;

                        cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                        cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                        //cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                        //cmd.Parameters["@error"].Direction = ParameterDirection.Output;
                        SqlDataAdapter adp = new SqlDataAdapter(cmd);

                        DataTable dt = new DataTable();

                        int rowsAffected = adp.Fill(dt);

                        if (rowsAffected > 0)
                        {
                            lstCUser.AddRange(dt.ConvertToListFromDataTableUser());
                        }

                        if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                        {
                            oCStatus.Success = true;
                            oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                        }
                        else
                        {
                            oCStatus.Success = false;
                            oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                            //oCStatus.StatusDetails = CAppErrorsConstants.SomethingWentWrong;
                        }
                    }
                    catch (Exception ex)
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = ex.Message;
                    }
                }
           

            return oCStatus;
        }

        /// <summary>
        /// This function is used to get complete user list with firstname and lastname only by requesting ajax layer function
        /// </summary>
        /// <param name="lstCUser">"out" the list of users</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus GetAllUserList(out List<CUser> lstCUser)
        {
            CStatus oCStatus = new CStatus();
            lstCUser = new List<CUser>();
            
                using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
                {
                    try
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand("r_get_all_users_list_procedure", con);
                        cmd.CommandType = CommandType.StoredProcedure;

                        cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                        cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                        //cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                        //cmd.Parameters["@error"].Direction = ParameterDirection.Output;
                        SqlDataAdapter adp = new SqlDataAdapter(cmd);

                        DataTable dt = new DataTable();

                        int rowsAffected = adp.Fill(dt);

                        if (rowsAffected > 0)
                        {
                            lstCUser.AddRange(dt.ConvertToListFromDataTableUser());
                        }

                        if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                        {
                            oCStatus.Success = true;
                            oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                        }
                        else
                        {
                            oCStatus.Success = false;
                            oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                            //oCStatus.StatusDetails = CAppErrorsConstants.SomethingWentWrong;
                        }
                    }
                    catch (Exception ex)
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = ex.Message;
                    }
                }
            

            return oCStatus;
        }

    }
}